-- SPDX-FileCopyrightText: Adam Evyčędo
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

---@diagnostic disable-next-line: unused-local, lowercase-global
function getAlerts(stopID, stopCode, tripID, lineID)
	if stopCode == '' then
		return '[]', ''
	end

	local http = require("http")
	local json = require("json")

	local error_struct = {
		httpResponseCode=0,
		message="",
		willNextRequestFail=false
	}

	local headers = {}
	headers['Content-Type'] = "application/x-www-form-urlencoded; charset=UTF-8"
	local response, error_message = http.post("https://www.peka.poznan.pl/vm/method.vm", {
    timeout="30s",
    headers=headers,
    body='method=findMessagesForBollard&p0={"symbol": "' .. stopCode .. '"}'
  })

	if response == nil then
		error_struct.message = "while getting alerts: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	if response.status_code ~= 200 then
		error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
		error_struct.httpResponseCode = response.status_code
		error_struct.willNextRequestFail = true
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	---@diagnostic disable-next-line: redefined-local
	local struct, error_message = json.decode(response.body)

	if struct == nil then
		error_struct.message = "while decoding alerts: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	local alerts = {}

	for i,entry in ipairs(struct.success) do
		local content = entry.content:gsub('<a href="[^"]+">', '')
		content = content:gsub('</a>', '')
		local url = string.match(entry.content, '<a href="([^"]+)">')

	  alerts[i] = {
	    timeRanges={
	    	{
	    		startDate=entry.startDate,
	    		endDate=entry.endDate
	    	}
	    },
	    headers={pl_PL=content},
	    descriptions={pl_PL=content},
	    urls={pl_PL=url},
	    cause=0,
	    effect=0
	  }
	end

	---@diagnostic disable-next-line: redefined-local
	local result, error_message = json.encode(alerts)

	if result == nil then
		error_struct.message = "while encoding result: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	return result, ""
end
